package cl.solidit.geomanagement.web.controller;

import java.io.ByteArrayInputStream;

import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.StringBuilderWriter;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import cl.solidit.geomanagement.persistance.UploadDAO;
import cl.solidit.geomanagement.persistance.model.Upload;
import cl.solidit.geomanagement.web.service.DataUploadService;

@Controller
public class DataUploadController {
	static final Logger log = Logger.getLogger(DataUploadController.class);
	@Autowired
	private UploadDAO uploadDAO;
	@Autowired
	private DataUploadService dataUploadService;

	@RequestMapping(value = "/data_upload", produces = "application/json", method = RequestMethod.POST)
	public ModelAndView upload(
			@RequestParam(value = "file", required = false) MultipartFile file,
			@RequestParam Integer tipo) {
		if (file == null)
			return this.uploadForm();
		Upload u = null;
		if (file != null && file.getSize() > 0) {
			try {
				StringBuilderWriter writer = new StringBuilderWriter();
				IOUtils.copy(new ByteArrayInputStream(file.getBytes()), writer);
				writer.flush();
				String data = writer.getBuilder().toString();
				String[] datasArray = data.split("\n");
				u = new Upload(datasArray.length);
				uploadDAO.save(u);
				if (tipo == 1)
					dataUploadService.loadPropiedades(u.getId(), datasArray);
				else
					dataUploadService.loadPersonas(u.getId(), datasArray);
			} catch (Exception e) {
				log.error("Error subiendo archivos", e);
			}
		}
		if (u != null)
			return new ModelAndView("uploading", "id", u.getId());
		return this.uploadForm();

	}

	@RequestMapping(value = "/data_upload", method = RequestMethod.GET)
	public ModelAndView uploadForm() {
		
		return new ModelAndView("upload");
	}

}
